package Comp355Final.main;

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;

import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;

public class InternetChClickListener implements OnClickListener{
	private Context parent;
	private String target_url;
	private String target_book;
	private String target_bookch;

	public InternetChClickListener(Context parent,String target_url,String target_book,String target_bookch){
		this.parent=parent;
		this.target_url=target_url;
		this.target_book=target_book;
		this.target_bookch=target_bookch;
	}
	public void onClick(View v) {
		//Utility.quick_dialog(target_url, parent);
		TCPGather tcpg = new TCPGather(target_url);
		//System.out.println(target_url);
		boolean succeededOrNot = tcpg.AskForHtml();
		String second_tar=new String();
		if(succeededOrNot)
		{
			ArrayList<String> Result_html=tcpg.GetTheResult();
			
			for(int i=0;i<Result_html.size();i++)
			{
				if(Result_html.get(i).toLowerCase().contains("frame") && Result_html.get(i).toLowerCase().contains("src") && Result_html.get(i).toLowerCase().contains("main"))
				{
					//Utility.quick_dialog(Result_html.get(i).toLowerCase().trim(), parent);
					second_tar=Result_html.get(i).toLowerCase().trim().replaceAll(" ", "").replace("<framename=\"main\"src=\"", "").replace("\">", "");
					//Utility.quick_dialog(second_tar, parent);
				}
			}
		}
		TCPGather tcpg2 = new TCPGather(second_tar);
		succeededOrNot = tcpg2.AskForHtml();
		if(succeededOrNot)
		{
			ArrayList<String> Result_html=tcpg2.GetTheResult();
			FileIO myfileio = new FileIO();
			if(!myfileio.check_Folderexisted(myfileio.get_sdcard_dest()+target_book))
			{
				myfileio.make_folder(myfileio.get_sdcard_dest()+target_book);
			}
			if(myfileio.check_Fileexisted(myfileio.get_sdcard_dest()+target_book+"/"+target_bookch+".txt"))
				FileIO.delete_file(myfileio.get_sdcard_dest()+target_book+"/"+target_bookch+".txt");
			Result_html=Utility.FilterOutHTML(Result_html,parent);
			myfileio.writefileOP(Result_html, myfileio.get_sdcard_dest()+target_book+"/"+target_bookch+".txt", "utf8");
			for(int i=0;i<Result_html.size();i++)
			{
				//new String(Result_html.get(i), "UTF-8");
				//System.out.println(Result_html.get(i));
				
				//PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
				 //out.println(Result_html.get(i));
			}
			Utility.quick_dialog("File created", parent);
		}
		// TODO Auto-generated method stub
		
	}

}
